package com.example.demo.component.proxy.cglib.interfacemaker;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.InterfaceMaker;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @ClassName Main
 * @Description
 * @date 2023/4/6 16:15
 * @Author yanceysong
 * @Version 1.0
 */
public class Main {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        InterfaceMaker im=new InterfaceMaker();
        im.add(ConcreteClassNoInterface.class);
        Class interfaceOjb=im.create();
        System.out.println(interfaceOjb.isInterface());//true
        System.out.println(interfaceOjb.getName());//net.sf.cglib.empty.Object$$InterfaceMakerByCGLIB$$13e205f
        //在根据接口创建对应的拦截 类
        Object obj = Enhancer.create(Object.class, new Class[]{ interfaceOjb },
                new MethodInterceptor() {
                    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
                        return "intercept!";
                    }
                });

        Method method = obj.getClass().getMethod("getConcreteMethodA", String.class);
        System.out.println(method.invoke(obj, "12345"));
        Method[] methods = interfaceOjb.getMethods();
        for(Method m:methods){
            System.out.println(m.getName());
        }
    }
}
